package com.xian.tszs.meal.component;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

@Component
public class WeChatComponent {

	@Value("${meal.xian.wechat.appid}")
	private String appid;

	@Value("${meal.xian.wechat.secret}")
	private String appsecret;
	
	/***
	 * 获取微信登录态
	* @author: MRC  
	* @date 2019年5月22日 下午2:47:01 
	* @return Map<String,String> 返回类型
	 */
	public Map<String, String> getWechatLoginStatus(String code) {

		Map<String, String> map = new HashMap<String, String>();
			
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret
				+ "&js_code=" + code + "&grant_type=authorization_code";
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 解析json
		JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
		String session_key = jsonObject.get("session_key") + "";
		String openid = jsonObject.get("openid") + "";
		
		map.put("openid", openid);
		map.put("session_key",session_key);
		
		return map;
		
	}

}
